package UserInterfase;

import core.IvoCheckers;
import java.io.*;
import java.net.*;
import core.Machine;
import core.PlayNetGame;
import core.SendBroadcast;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.*;

public class JoinGameWindow extends JDialog {

    private javax.swing.JButton FindButton;
    private javax.swing.JList GameList;
    private javax.swing.JButton JoinButton;
    private javax.swing.JScrollPane ScrollPane;
    private javax.swing.JButton AddButton;
    private javax.swing.JTextField AddIP;
    private javax.swing.JLabel AddLabel;
    private static List<Machine> serverList;
    private static int port = 5555;
    private static int SERVER_RESPONSE_TIMEOUT = 15 * 1000;
    public void initUI(int posX, int posY)
    {
        serverList = new ArrayList<Machine>();
        ScrollPane = new javax.swing.JScrollPane();
        GameList = new javax.swing.JList();
        FindButton = new javax.swing.JButton();
        JoinButton = new javax.swing.JButton();
        AddLabel = new javax.swing.JLabel();
        AddIP = new javax.swing.JTextField();
        AddButton = new javax.swing.JButton();
        
        setLocation(posY, posY);
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });
        
        GameList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        ScrollPane.setViewportView(GameList);

        FindButton.setText("Find");
        FindButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                FindButtonActionPerformed(evt);
            }
        });

        JoinButton.setText("Join");
        JoinButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JoinButtonActionPerformed(evt);
            }
        });

        AddLabel.setText("Add Server IP");

        AddButton.setText("Add");
        AddButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AddButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(ScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 154, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(35, 35, 35)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(AddLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(AddIP, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(AddButton, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(66, 66, 66))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(FindButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 226, Short.MAX_VALUE)
                        .addComponent(JoinButton, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(22, 22, 22))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(ScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(17, 17, 17)
                        .addComponent(AddLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(AddIP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(AddButton)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(FindButton)
                    .addComponent(JoinButton))
                .addContainerGap(16, Short.MAX_VALUE))
        );

        pack();

        this.setTitle("Find Game");
	this.setSize(400, 350);
       // this.setAlwaysOnTop(true);
        this.setModal(true);
        this.setVisible(true);
    }

    private void FindButtonActionPerformed(java.awt.event.ActionEvent evt) {
        boolean exitCode;
        serverList.clear();
        exitCode = SendBroadcast.findAllServers(serverList);
        if (!exitCode)
        {
            return;
        }
        Vector data = new Vector();
        int i = 0;
        for (i = 0; i < serverList.size(); i++)
        {
            data.add(serverList.get(i).MachineName);
        }
        GameList.removeAll();
        GameList.setListData(data);
    }
    private void JoinButtonActionPerformed(java.awt.event.ActionEvent evt) {
        String machineName = (String)GameList.getSelectedValue();
        int index = GameList.getSelectedIndex();
        if (serverList.get(index).MachineName.equals(machineName))
        {
            Socket socket = null;
            try {
                socket = new Socket(serverList.get(index).IP_String, port);
                socket.setSoTimeout(SERVER_RESPONSE_TIMEOUT);
            } catch (SocketTimeoutException ex) {
                JOptionPane.showMessageDialog(null, "Server didn`t response");
            } catch (UnknownHostException ex) {
                JOptionPane.showMessageDialog(null,
                        "There is problem. Connection faild!");
                ex.printStackTrace();
                return;
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null,
                        "There is problem. Connection faild!");
                ex.printStackTrace();
                return;
            }
            System.out.println("Connect to server");
            try {
                PlayNetGame.setMSocketReader(new BufferedReader(
                        new InputStreamReader(socket.getInputStream())));
                SimpleBoard.setMSocketWriter(new PrintWriter(
                        new OutputStreamWriter(socket.getOutputStream())));
            }
            catch (IOException ex)
            {
                System.out.println("Can not create reader and writer for socket!");
                ex.printStackTrace();
                return;       
            }
            SimpleBoard.setIsLightColor(false);
            IvoCheckers.startNewGame();
            IvoCheckers.getGame().setPlayerTurn(true);
            SimpleBoard.setIsNetGame(true);
            
            IvoCheckers.getGame().setBlockMove(true);
            PlayNetGame.setSimpleBoard(SimpleGUI.getBoard());
            PlayNetGame netGame = new PlayNetGame();
            netGame.start();
            setVisible(false);
            dispose();
             JOptionPane.showMessageDialog(null,
                        "Your oponent is first!");
            
        }

    }
    private void AddButtonActionPerformed(java.awt.event.ActionEvent evt) {
        String value = AddIP.getText();
        if (value.length() > "255.255.255.255".length())
        {
            JOptionPane.showMessageDialog(null,
                        "Too long string for IP address");
            return;
        }
        Machine server = null;
        server = SendBroadcast.findServer(value);
        if (server == null)
        {
            JOptionPane.showMessageDialog(null,
                        "Can`t find destination server! Try again!");
            return;
        }
        serverList.add(server);
        GameList.removeAll();
        Vector data = new Vector();
        int i = 0;
        for (i = 0; i < serverList.size(); i++)
        {
            data.add(serverList.get(i).MachineName);
        }
        GameList.setListData(data);
    }
    private void formWindowClosed(java.awt.event.WindowEvent evt) {
        
    }
}
